package cn.shujuhai.workflow.service.flow;

import cn.shujuhai.common.pluging.data.ResultVo;
import cn.shujuhai.workflow.service.FormDataService;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.flowable.engine.*;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: ZhangDeZhong
 * @Date: 2025/4/1 09:48
 * @Description:
 **/

@Service
@RequiredArgsConstructor
public class ProcessDeployService {
    private final RepositoryService repositoryService;
    private final RuntimeService runtimeService;
    private final TaskService taskService;
    private final HistoryService historyService;
    private final ProcessEngine processEngine;
    private final FormDataService formDataService;


    public ResultVo<?> processDeployList(int pageNum, int pageSize) {
        List<ProcessDefinition> processDefinitionList = this.repositoryService.createProcessDefinitionQuery()
                .orderByDeploymentId().desc()
                .listPage((pageNum - 1) * pageSize, pageSize);
        List<Map<String, Object>> listMap = new ArrayList<>();

        for (ProcessDefinition pd : processDefinitionList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", pd.getId());
            map.put("name", pd.getName());
            map.put("key", pd.getKey());
            map.put("version", pd.getVersion());
            map.put("deploymentId", pd.getDeploymentId());
            map.put("resourceName", pd.getResourceName());
            map.put("diagramResourceName", pd.getDiagramResourceName());
            map.put("suspensionState", pd.isSuspended() ? "SUSPENDED" : "ACTIVE");
            map.put("isSuspended", pd.isSuspended());
            listMap.add(map);
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(listMap);
        pageInfo.setTotal(this.repositoryService.createProcessDefinitionQuery().count());
        return ResultVo.success(pageInfo);

    }

    public ResultVo<?> enable(String id) {
        try {
            ProcessDefinition processDefinition = repositoryService.getProcessDefinition(id);
            if (processDefinition.isSuspended()) {
                repositoryService.activateProcessDefinitionById(id);
            } else {
                repositoryService.suspendProcessDefinitionById(id);
            }
            return ResultVo.success();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
